package urlhelper

import (
	"io"
	"net/http"
	"net/url"
	"os"
	"path"
	"strconv"
	"strings"

	"gitee.com/fkil555/gin-extend/helpers/filehelper"
)

// URI中的数字替换为{num}
func ReplaceURI(uri string) string {
	// 按/切割
	parts := strings.Split(strings.Trim(uri, "/"), "/")

	// 数字替换为{num}
	replaced := make([]string, 0)
	for i := 0; i < len(parts); i++ {
		if _, err := strconv.Atoi(parts[i]); err == nil { // 数字替换为{num}
			replaced = append(replaced, "{num}")
		} else {
			replaced = append(replaced, parts[i])
		}
	}
	// 用/连接起来
	return strings.Join(replaced, "/")
}

// 通过url获取对应的文件名
func UrlBase(uri string) (file string, err error) {
	u, err := url.Parse(uri)
	if err != nil {
		return
	}
	file = path.Base(u.Path)
	return
}

func DownloadUrl(dst, url string) error {
	dir := filehelper.Dir(dst)
	if !filehelper.IsDir(dir) {
		os.Mkdir(dir, 0666)
	}
	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return err
	}

	return nil
}
